<script setup>
import { ref, onMounted, onUpdated, onBeforeMount, nextTick } from 'vue'
import axios from 'axios'
import dialoged from './components/dialog.vue'
import { ElMessage } from 'element-plus'
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
import Sortable from 'sortablejs';
// import { VueDraggableNext } from 'vue-draggable-next';


const inputSeaech = ref(null)
const selectValue = ref(null)
const options = [
  {
    value: '男',
    label: '男',
  },
  {
    value: '女',
    label: '女',
  },
]
const shortcuts = [
  {
    text: 'Last week',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: 'Last month',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: 'Last 3 months',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]
const dateValue = ref('')
const tableData = [
  {
    date: '2016-05-03',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    date: '2016-05-02',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    date: '2016-05-04',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    date: '2016-05-01',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
]
// const currentPage4 = ref(1)
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}
const handleCurrentChange = (val) => {
  page.value = val
  getList()
}

const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const userList = ref([])
const getList = () => {
  axios({
    url: '/user/list',
    method: 'post',
    data: {
      page: page.value,
      pageSize: pageSize.value,
      inputSeaech: inputSeaech.value,
      selectValue: selectValue.value
    }
  }).then((res) => {
    userList.value = res.data.list
    total.value = res.data.total
  })
}
getList()

//搜索
const onSearch = () => { getList() }
//重置搜索
const onClose = () => {
  getList()
}
//筛选性别
const onChangeSelect = () => {
  getList()
}

let ids = ref([])
//单选/多选删除
const handleChooseRow = (val) => {
  ids.value = val.map((item) => item.id)
}
//新增
const dialogRef = ref(null)
const handerAdd = () => {
  dialogRef.value.openDialog(null)
}
//编辑
const handleEdit = (index, row) => {
  dialogRef.value.openDialog(row)
}

//删除
const handleDelete = (index, row) => {
  axios({
    url: '/user/delete',
    method: 'post',
    data: {
      id: row.id
    }
  }).then((res) => {
    getList()
    ElMessage({
      message: '删除成功',
      type: 'success',
    })
  })
}
//接受子组件数据：确认修改和新增
const onchangeList = (obj, isRdit) => {
  if (isRdit) {
    axios({ url: '/user/edit', method: 'post', data: obj }).then((res) => {
      ElMessage({
        message: '修改成功',
        type: 'success',
      })
    })
  } else {
    axios({ url: '/user/add', method: 'post', data: obj }).then((res) => {
      ElMessage({
        message: '新增成功',
        type: 'success',
      })
    })
  }

  getList()
}
//是否禁用
const handleChange = (row) => {
  axios({
    url: '/user/isDisabled',
    method: 'post',
    data: {
      id: row.id,
      isDisabled: row.isDisabled
    }
  }).then((res) => {
    getList()
  })
}
//重置
const handerReset = () => {
  inputSeaech.value = null
  selectValue.value = null
  axios({
    url: '/user/reset',
    method: 'post',
    data: {
      page: page.value,
      pageSize: pageSize.value,
    }
  }).then((res) => {
    userList.value = res.data.list
    total.value = res.data.total

  })

}

//批量删除
const handerBatchDelete = () => {
  axios({ url: '/user/batchDelete', method: 'post', data: { ids: ids.value } }).then((res) => {
    getList()
    // ElMessage({
    //   message: '删除成功',
    //   type: 'success',
    // })
  })
}
//导出函数
function exportToExcel(jsonData, fileName) {
  // 将 JSON 数据转换为工作表对象
  const worksheet = XLSX.utils.json_to_sheet(jsonData);

  // 创建一个新的工作簿并将工作表添加到其中
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

  // 将工作簿导出为 Blob 对象
  const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'binary' });
  const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });

  // 使用 FileSaver.js 保存 Blob 对象为文件
  saveAs(blob, `${fileName}.xlsx`);
}

// 字符串到 ArrayBuffer 的转换函数
function s2ab(s) {
  const buf = new ArrayBuffer(s.length);
  const view = new Uint8Array(buf);
  for (let i = 0; i < s.length; i++) {
    view[i] = s.charCodeAt(i) & 0xff;
  }
  return buf;
}
// 导出
const handerExport = () => {
  exportToExcel(userList.value, '用户数据');
}


const table = ref(null)
const sortable = ref(null)
const initSortable = () => {
  const el = table.value.$el.querySelector('.el-table__body-wrapper tbody');
  sortable.value = Sortable.create(el, {
    onEnd: ({ newIndex, oldIndex }) => {
      nextTick(() => {
        // 处理拖拽结束后的逻辑，比如更新数据顺序  
        const movedItem = userList.value.splice(oldIndex, 1)[0];
        userList.value.splice(newIndex, 0, movedItem);
        console.log(userList.value);
      })
    },
  });
}
onMounted(() => {
  initSortable()
})
onBeforeMount(() => {
  if (sortable.value) {
    sortable.value.destroy()
  }
})

</script>

<template>
  <div class="container-user">
    <div class="header">
      <div class="serach">
        <el-input @keyup.enter.native="onSearch" @clear="onClose" v-model="inputSeaech" style="width: 150px"
          placeholder="serach" clearable>
          <template #prefix>
            <el-icon class="el-input__icon">
              <search />
            </el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="onSearch">搜索</el-button>
      </div>
      <el-select @change="onChangeSelect" @clear="onClose" v-model="selectValue" clearable placeholder="Select"
        style="width: 240px">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>

      <el-date-picker v-model="dateValue" type="daterange" unlink-panels range-separator="To"
        start-placeholder="Start date" end-placeholder="End date" :shortcuts="shortcuts" size="default" />

      <el-button type="primary" @click="handerAdd">新增</el-button>
      <el-button type="primary" @click="handerReset">重置</el-button>

      <el-button type="primary" @click="handerBatchDelete">批量删除</el-button>
      <el-button type="primary" @click="handerExport">导出</el-button>


    </div>
    <div class="table">
      <!-- <vue-draggable-next :options="dragOptions"> -->
      <el-table ref="table" :data="userList" row-key="id" height="520" border style="width: 100%;" highlight-current-row
        @selection-change="handleChooseRow">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="username" label="姓名" />
        <el-table-column prop="age" label="年龄" />
        <el-table-column prop="gender" label="性别" />
        <el-table-column prop="phone" label="手机号" width="auto" min-width="100px" />
        <el-table-column prop="address" label="地址" width="auto" min-width="160px" />
        <el-table-column prop="isDisabled" label="是否禁用">
          <template #default="scope">
            <el-switch v-model="scope.row.isDisabled" @change="handleChange(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column prop="registerTime" label="注册时间" width="auto" min-width="150px" />
        <el-table-column label="操作" width="auto" min-width="120px">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-popconfirm title="确认删除吗?" @confirm="handleDelete(scope.$index, scope.row)">
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- </vue-draggable-next> -->

      <div class="page-size">
        <el-pagination :page-sizes="[5, 10, 15, 20]" :background="true" layout="total, sizes, prev, pager, next, jumper"
          :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>

    <dialoged ref="dialogRef" @update="onchangeList"></dialoged>
  </div>
</template>

<style scoped lang="scss">
.container-user {
  .header {
    width: 100%;
    height: 100px;
    background-color: #fff;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    padding: 0 20px;
    gap: 30px;

    .serach {
      display: flex;
      gap: 10px;
    }
  }

  .table {
    width: 100%;
    height: 500px;

    // background-color: goldenrod;
    .page-size {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}

.ghost {
  opacity: 0.5;
  background: #c8ebfb;
}
</style>